﻿using LeSoft.Application.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Util;
using LeSoft.Application.Cache;
using LeSoft.Application.Entity;
using LeSoft.Application.Bussiness;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class CS_EnergyMeterReadingController : MvcControllerBase
    {
        #region  视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "抄表", "Index")]
        public ActionResult Index()
        {
            var AuditSetting = new SettingBLL().GetWorkAuditEntityByCode(((int)CodeRuleEnum.EnergyMeterBill).ToString());
            ViewBag.AuditSetting = AuditSetting == null ? "" : AuditSetting.Id;
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "抄表", "Form")]
        public ActionResult Form()
        {
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(((int)CodeRuleEnum.EnergyMeterBill).ToString());
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "抄表", "Detail")]
        public ActionResult Detail()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "费表", "AddMeter")]
        public ActionResult AddMeter()
        {
            return View();
        }

        #endregion

        #region 获取数据

        #region 查询单据状态树
        private List<TreeStatusEntity> GetList()
        {
            List<TreeStatusEntity> li = new List<TreeStatusEntity>();
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.All), EnergyMeterBillStateEnum.All.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.Waiting), EnergyMeterBillStateEnum.Waiting.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.Sending), EnergyMeterBillStateEnum.Sending.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.Handling), EnergyMeterBillStateEnum.Handling.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.Completed), EnergyMeterBillStateEnum.Completed.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.Submited), EnergyMeterBillStateEnum.Submited.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.AuditSuccess), EnergyMeterBillStateEnum.AuditSuccess.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.AuditRefuse), EnergyMeterBillStateEnum.AuditRefuse.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.Rejected), EnergyMeterBillStateEnum.Rejected.ToString(), 0));
            li.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(EnergyMeterBillStateEnum.Cancel), EnergyMeterBillStateEnum.Cancel.ToString(), 0));
            return li;
        }

        /// <summary>
        /// 状态树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetStateTreeList()
        {
            var data = GetList();
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text + "<" + item.Count + ">";
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        #endregion

        /// <summary>
        /// 获取抄表单列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "抄表", "GetPageList")]
        public ActionResult GetPageList(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var data = new EnergyBLL().GetPageList(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 获取单据信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "抄表", "GetFormInfo")]
        public ActionResult GetFormInfo(string keyValue)
        {
            var List = new EnergyBLL().GetReadingEnergyMeterList(keyValue).Join(new EnergyBLL().GetInstanceList(), x => x.EnergyMeterInstanceId, y => y.Id, (x, y) => new
            {
                x.Id,
                x.EnergyMeterInstanceId,
                x.AdjustVolume,
                x.BatchDate,
                x.BatchNo,
                x.LastBatchDate,
                x.LastScaleDate,
                x.LastScaleNum,
                x.Price,
                x.PStructId,
                x.ScaleDate,
                x.ScaleNum,
                x.State,
                x.UnitPrice,
                x.Volume,
                y.Name,
                y.Type,
                y.Code,
                y.PSMemo
            }).Join(new PStructCache().GetList(), x => x.PStructId, y => y.Id, (x, y) => new
            {
                x.Id,
                x.EnergyMeterInstanceId,
                x.AdjustVolume,
                x.BatchDate,
                x.BatchNo,
                x.LastBatchDate,
                x.LastScaleDate,
                x.LastScaleNum,
                x.Price,
                x.PStructId,
                x.ScaleDate,
                x.ScaleNum,
                x.State,
                x.UnitPrice,
                x.Volume,
                x.Name,
                x.Type,
                x.Code,
                x.PSMemo,
                y.AllName
            });
            var task = new SysTaskBLL().GetList().Where(t => t.SourceId == keyValue);
            var taskSend = task != null ? task.FirstOrDefault(t => t.Type == 2) : null;
            var Worker = new AccountBLL().GetEntityByAccount(OperatorProvider.Provider.Current().Account).SourceId;
            var IsSendWay = taskSend == null ? false : new TaskUserBLL().ValidateUser(taskSend.Id, Worker) ? true : false;
            var taskDispose = task != null ? task.FirstOrDefault(t => t.State < 3 && t.Type == 1) : null;
            var IsDispose = taskDispose == null ? false : new TaskUserBLL().ValidateUser(taskDispose.Id, Worker) ? true : false;
            var data = new
            {
                Bill = new EnergyBLL().GetEnergyMeterBill(keyValue),
                List = List,
                IsSendWay = IsSendWay,
                IsDispose = IsDispose
            };
            return Content(data.ToJson());
        }


        /// <summary>
        /// 获取抄表明细
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        /// 用于查看所有表抄表记录
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "抄表", "GetPageDetailList")]
        public ActionResult GetPageDetailList(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                queryParam["OrganizeId"] = new OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                queryJson = queryParam.ToJson();
            }
            var data = new EnergyBLL().GetPageDetailList(pagination, queryJson);
            //var dataLinq = from x in data
            //                  join b in new EnergyBLL().GetInstanceList() on x.EnergyMeterInstanceId equals b.Id into temp
            //                  from tt in temp.DefaultIfEmpty()
            //                  join a in new PStructCache().GetList() on x.PStructId equals a.Id into y
            //                  from z in y.DefaultIfEmpty()
            //                  select new
            //                  {
            //                      x.Id,
            //                      x.EnergyMeterInstanceId,
            //                      x.AdjustVolume,
            //                      x.BatchDate,
            //                      x.BatchNo,
            //                      x.LastBatchDate,
            //                      x.LastScaleDate,
            //                      x.LastScaleNum,
            //                      x.Price,
            //                      x.PStructId,
            //                      x.ScaleDate,
            //                      x.ScaleNum,
            //                      x.State,
            //                      x.UnitPrice,
            //                      x.Volume,
            //                      Type = tt == null ? "" : tt.Type,//这里主要第二个集合有可能为空。需要判断
            //                      Code = tt == null ? "" : tt.Code,
            //                      PSMemo = tt == null ? "" : tt.PSMemo,
            //                      Name = tt == null ? "" : tt.Name,
            //                      AllName = z == null ? "" : z.AllName
            //                  };
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        /// <summary>
        /// 房产+装表树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "抄表", "GetTreeList")]
        public ActionResult GetTreeList(string OrganizeId)
        {
            var data = new PStructBLL().GetList().Where(t => t.EnabledMark == 1);
            var data2 = new EnergyBLL().GetInstanceList().Where(t => t.EnabledMark == 1);
            if (!OrganizeId.IsEmpty())
            {
                data = data.Where(t => t.OrganizeId == OrganizeId);
                data2 = data2.Where(t => t.OrganizeId == OrganizeId);
            }
            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (PStructEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                if (item.ParentId == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.ParentId;
                tree.Attribute = "type";
                tree.AttributeValue = item.Type.ToString();
                treeList.Add(tree);
            }
            foreach (EnergyMeterInstanceEntity item in data2)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                if (item.ParentId == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                if (item.ParentId == "0") tree.parentId = item.PStructId;
                else tree.parentId = item.ParentId;
                tree.Attribute = "type";
                tree.AttributeValue = "8";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "重复编码验证", "ExistCode")]
        public ActionResult ExistCode(string Code, string keyValue)
        {
            bool IsOk = new EnergyBLL().ExistCode(Code, keyValue);
            return Content(IsOk.ToString());
        }

        /// <summary>
        /// 用于新增单据时添加明细
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "抄表", "GetEneryMeterPageList")]
        public ActionResult GetEneryMeterPageList(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var queryParam = queryJson.ToJObject();
            if (!string.IsNullOrEmpty(queryJson))
            {
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = new OrganizeCache().GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    queryParam["OrganizeId"] = OrganizeId;
                }
                queryJson = queryParam.ToJson();
            }
            var pstructData = new PStructCache().GetList();
            var data = new EnergyBLL().GetEneryMeterPageList(pagination, queryJson).Join(pstructData, x => x.PStructId, y => y.Id, (x, y) => new
            {
                x.BatchDate,
                x.Code,
                x.EnergyMeterId,
                x.EnergyType,
                x.Id,
                x.MaxVolume,
                x.MeterType,
                x.MinVolume,
                x.Name,
                x.Nature,
                x.OrganizeId,
                x.PSMemo,
                x.PStructId,
                x.ScaleDate,
                x.ScaleNum,
                x.Type,
                x.UnitPrice,
                x.Volume,
                y.AllName
            });
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "抄表审核记录", "GetAudit")]
        public ActionResult GetAudit(string BillId)
        {
            var AuditSetting = new SettingBLL().GetWorkAuditEntityByCode(((int)CodeRuleEnum.EnergyMeterBill).ToString());
            var obj = new List<object>();
            if (AuditSetting != null)
            {
                var AuditMemoentity = AuditSetting.AuditMemo.ToList<WorkAuditMemoEntity>();
                var AuditRecord = new AuditRecordBLL().GetList(BillId);
                foreach (var item in AuditMemoentity)
                {
                    var data = AuditRecord.FirstOrDefault(t => t.Level == item.Level);
                    if (data != null)
                    {
                        var Acc = new AccountBLL().GetEntity(data.AuditMan);
                        obj.Add(new { item.RoleType, item.RoleId, Level = item.Level, data.AuditTime, data.AuditState, AuditMan = Acc != null ? Acc.Name : data.AuditMan, data.AuditMemo });
                    }
                    else
                        obj.Add(new { item.RoleType, item.RoleId, Level = item.Level });
                }
            }
            return Content(obj.ToJson());
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存单据
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="Bill"></param>
        /// <param name="listJson"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存单据", "SaveForm")]
        public ActionResult SaveForm(string keyValue, string Bill, string listJson)
        {
            try
            {
                ReadingEnergyMeterBillEntity entity = Bill.ToObject<ReadingEnergyMeterBillEntity>();
                List<ReadingEnergyMeterDetailEntity> list = listJson.ToObject<List<ReadingEnergyMeterDetailEntity>>();
                new EnergyBLL().SaveForm(keyValue, entity, list);
                return Success("操作成功！");
            }
            catch (Exception e)
            {
                return Error("操作失败!" + e.Message);
            }

        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "提交", "SubmitForm")]
        public ActionResult SubmitForm(string keyValue)
        {
            try
            {
                new EnergyBLL().SubmitForm(keyValue);
                return Success("操作成功！");
            }
            catch (Exception e)
            {
                return Error("操作失败!" + e.Message);
            }
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="auditRecordEntity"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "审核", "AuditForm")]
        public ActionResult AuditForm(string keyValue, AuditRecordEntity auditRecordEntity)
        {
            try
            {
                new EnergyBLL().AuditForm(keyValue, auditRecordEntity);
                return Success("操作成功！");
            }
            catch (Exception e)
            {
                return Error("操作失败!" + e.Message);
            }
        }

        #endregion
    }
}
